package com.sebiotec.glp.limoapp;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Environment;
import android.util.Log;

import androidx.multidex.MultiDex;

import com.alibaba.android.arouter.launcher.ARouter;
import com.allen.library.RxHttpUtils;
import com.allen.library.config.OkHttpConfig;
import com.allen.library.gson.GsonAdapter;
import com.allen.library.http.SSLUtils;
import com.allen.library.interceptor.Level;
import com.allen.library.interceptor.LoggingInterceptor;

import com.allen.library.interceptor.RefreshTokenInterceptor;
import com.sebiotec.basecommon.BuildConfig;
import com.sebiotec.basecommon.utils.constant.SjmConstant;
import com.sebiotec.basecommon.utils.global.SMJApp;

import com.sebiotec.basecommon.utils.language.LocalManageUtil;


import com.sebiotec.glp.limoapp.service.RepetitionService;

import com.github.jokar.multilanguages.library.LanguageLocalListener;
import com.github.jokar.multilanguages.library.MultiLanguage;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.bugly.crashreport.CrashReport;
import com.xuexiang.keeplive.KeepLive;
import com.xuexiang.keeplive.config.ForegroundNotification;
import com.xuexiang.keeplive.config.ForegroundNotificationClickListener;
import com.xuexiang.keeplive.config.KeepLiveService;
import com.xuexiang.xui.XUI;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;

import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class APP extends SMJApp {
    private MyUncaughtExceptionHandler uncaughtExceptionHandler;
    private static String packgeName;

    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        packgeName = getPackageName();
        MultiLanguage.init(new LanguageLocalListener() {
            @Override
            public Locale getSetLanguageLocale(Context context) {
                //return your local settings
                return LocalManageUtil.getSetLanguageLocale(context);
            }
        });
//        LocalManageUtil.saveSelectLanguage(this, 3);
        initRxHttpUtils();
//        initKeepLive();
        MultiLanguage.setApplicationLanguage(this);
        XUI.init(this); //初始化UI框架
        XUI.debug(true);  //开启UI框架调试日志
        ARouter.init(this);

        CrashReport.initCrashReport(getApplicationContext());
    }


    @Override
    protected void attachBaseContext(Context base) {
        MultiDex.install(this);
        LocalManageUtil.saveSystemCurrentLanguage(base);
        super.attachBaseContext(MultiLanguage.setLocal(base));


    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        /**
         The user saves the system selection language when switching languages on the system settings page (in order to select when the system language is used, if it is not saved, it will not be available after switching languages)
         **/
        LocalManageUtil.saveSystemCurrentLanguage(getApplicationContext(), newConfig);
        MultiLanguage.onConfigurationChanged(getApplicationContext());
    }

    private void initRxHttpUtils() {

        RxHttpUtils
                .getInstance()
                .init(this)
                .config()
                //自定义factory的用法
                .setConverterFactory(ScalarsConverterFactory.create())
                .setConverterFactory(GsonConverterFactory.create(GsonAdapter.buildGson()))
                .setCallAdapterFactory(RxJava2CallAdapterFactory.create())

                //

                //开启全局配置
                .setOkClient(createOkHttp());


    }

    private OkHttpClient createOkHttp() {


        OkHttpClient okHttpClient = new OkHttpConfig
                .Builder(this)
                .setCache(false)
                .setHasNetCacheTime(10)//默认有网络时候缓存60秒
                .setReadTimeout(20)
                //全局超时配置
                .setWriteTimeout(20)

                .setAddInterceptor(new LoggingInterceptor
                        .Builder()//构建者模式

                        .loggable(BuildConfig.DEBUG) //是否开启日志打印
                        .setLevel(Level.BASIC) //打印的等级
                        .log(Platform.INFO) // 打印类型
                        .request("Request") // request的Tag
                        .response("Response")// Response的Tag
                        .addHeader("log-header", "I am the log request header.") // 添加打印头, 注意 key 和 value 都不能是中文
                        .build(),new RefreshTokenInterceptor())
                //全局超时配置
                .setConnectTimeout(15)
                //全局是否打开请求log日志
                .setDebug(BuildConfig.DEBUG)
                .build();

        return okHttpClient;
    }

    private void cauchException() {
        System.out
                .println("-----------------------------------------------------");
        // 程序崩溃时触发线程
        uncaughtExceptionHandler = new MyUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
    }

    private class MyUncaughtExceptionHandler implements
            Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            // 保存错误日志
//            saveCatchInfo2File(ex);
            // 如果报错就不进行重启
//			android.os.Process.killProcess(android.os.Process.myPid());
            //System.exit(0);
        }

    }

    ;


    /**
     * 保存错误信息到文件中
     *
     * @return 返回文件名称
     */
    private String saveCatchInfo2File(Throwable ex) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String sb = writer.toString();

        // Toasty.INSTANCE.showToast(application,sb);
        try {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String time = formatter.format(new Date());
            String fileName = time + ".txt";
            System.out.println("fileName:" + fileName);
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                String filePath = SjmConstant.BASE_DIR + SjmConstant.DIR
                        + packgeName + "/crash/";
                File dir = new File(filePath);
                if (!dir.exists()) {
                    if (!dir.mkdirs()) {
                        // 创建目录失败: 一般是因为SD卡被拔出了
                        return "";
                    }
                }

                FileOutputStream fos = new FileOutputStream(filePath + fileName);
                fos.write(sb.getBytes());
                fos.close();
                // 文件保存完了之后,在应用下次启动的时候去检查错误日志,发现新的错误日志,就发送给开发者
            }
            return fileName;
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 初始化保活，配置完成后即可实现程序的保活
     */
    private void initKeepLive() {
        //定义前台服务的默认样式。即标题、描述和图标
        ForegroundNotification notification = new ForegroundNotification("Service", "Service is running...", R.mipmap.ic_launcher,
                //定义前台服务的通知点击事件
                new ForegroundNotificationClickListener() {
                    @Override
                    public void onNotificationClick(Context context, Intent intent) {

                    }
                })
                //要想不显示通知，可以设置为false，默认是false
                .setIsShow(false);
        //启动保活服务
        KeepLive.startWork(this, KeepLive.RunMode.ROGUE, notification,
                //你需要保活的服务，如socket连接、定时任务等，建议不用匿名内部类的方式在这里写

                new KeepLiveService() {
                    /**
                     * 运行中
                     * 由于服务可能会多次自动启动，该方法可能重复调用
                     */
                    @Override
                    public void onWorking() {
                        Log.d("aa","服务运行中");
                        //可以做一些保活的处理，比如说恢复推送连接等
                        Timer timer = new Timer();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                Log.d("aa","服务运行中1");
                                Intent intent = new Intent(context, RepetitionService.class);
                                startService(intent);  //do something
                            }
                        }, 6000);//延时1s执行
                    }

                    /**
                     * 服务终止
                     * 由于服务可能会被多次终止，该方法可能重复调用，需同onWorking配套使用，如注册和注销broadcast
                     */
                    @Override
                    public void onStop() {
                        //该回调方法可能会不回调
                    }
                }
        );
    }
}
